/**
 * DB库
 */
const MongoClient = require('mongodb').MongoClient
const Config = require('./config')

class Db {

  /* 单例：解决多次实例化实例不共享的问题 */
  static getInstance() {
    if (!Db.instance) {
      Db.instance = new Db()
    }
    return Db.instance
  }

  constructor() {
    //属性，放db对象
    this.dbClient = ''
    //初始化的时候连接数据库
    //this.connect()
  }

  /* 连接数据库 */
  connect() {
    let _that = this
    return new Promise((resolve, reject) => {
      
      if (!_that.dbClient) { //解决数据库多次了解的问题
        MongoClient.connect(Config.dbUrl, { useUnifiedTopology: true }, (error, client) => {
          if (error) {
            reject(error)
          } else {
            _that.dbClient = client.db(Config.dbName)
            resolve(_that.dbClient)
          }
        })
      } else {
        resolve(_that.dbClient)
      }
      
    })
  }

  /*  */
  find(collectionName, json) {
    return new Promise((resolve, reject) => {
      this.connect().then((db) => {
        const result = db.collection(collectionName).find(json)
        result.toArray((err, docs) => {
          if (err) {
            reject(err)
            return
          }
          resolve(docs)
        })
      })
    })
  }

  update() {

  }

  insert() {

  }

}

const myDb = Db.getInstance()

setTimeout(() => {
  console.time('start')
  myDb.find('user', {}).then(data => {
    // console.log(data)
    console.timeEnd('start')
  })
}, 100)


setTimeout(() => {
  console.time('start1')
  myDb.find('user', {}).then(data => {
    // console.log(data)
    console.timeEnd('start1')
  })
}, 1000)

const myDb1 = Db.getInstance()

setTimeout(() => {
  console.time('start2')
  myDb1.find('user', {}).then(data => {
    // console.log(data)
    console.timeEnd('start2')
  })
}, 3000)


setTimeout(() => {
  console.time('start3')
  myDb1.find('user', {}).then(data => {
    // console.log(data)
    console.timeEnd('start3')
  })
}, 5000)